"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const m_base_1 = tslib_1.__importDefault(require("../utils/m-base"));
const m_file_1 = tslib_1.__importDefault(require("../utils/m-file"));
const m_cmder_1 = tslib_1.__importDefault(require("./m-cmder"));
/**文件书写器基类 */
class MWriter {
    /**是否已加载 */
    static loaded = false;
    /**子类注册表 */
    static writers = {};
    /**顶级参数 */
    _parm = {};
    /**顶级参数 */
    get parm() {
        return this._parm;
    }
    /**解析后的数据 */
    get data() {
        return this.parm.result;
    }
    get dir() {
        const { apiPath } = this.parm;
        return apiPath;
    }
    /** 注册书写器类 */
    static register(writerName, writer) {
        MWriter.writers[writerName] = writer;
    }
    /** 动态加载所有子类 */
    static async loadWriters() {
        const path = m_file_1.default.joinDirPath(__dirname, "../subWriters");
        const files = await m_file_1.default.readDir(path);
        for (const file of files) {
            if (!file.endsWith(".ts") && !file.endsWith(".js"))
                continue;
            require(m_file_1.default.joinDirPath(path, file));
        }
        MWriter.loaded = true;
    }
    /**创建书写器 */
    static async write(parm) {
        const { writerName } = parm;
        if (!MWriter.loaded)
            await MWriter.loadWriters();
        const WriterClass = MWriter.writers[writerName];
        if (!WriterClass)
            throw new Error(`未找到书写器: ${writerName}`);
        const writer = new WriterClass(parm);
        await writer.clearFiles();
        await Promise.all([
            writer.writeEnums(),
            writer.writeModels(),
            writer.writeMethods(),
        ]);
    }
    /**实例化书写器 */
    constructor(parm) {
        this._parm = parm;
    }
    /**获取文件顶部提示内容 */
    getFileTips() {
        const cmd = m_cmder_1.default.encodeArgs(this.parm);
        return [
            "/* eslint-disable */",
            ...m_base_1.default.toCommonNote("此文件代码由接口发布器swg生成，请勿手动修改。"),
            ...m_base_1.default.toCommonNote(`命令行中执行 '${cmd["cmd"]}' 将重新生成。`),
            "\t",
        ];
    }
    /**清空文件 */
    async clearFiles() {
        const { dir } = this;
        await m_file_1.default.deletePath(dir);
    }
}
exports.default = MWriter;
